package com.etc.controller;

import com.etc.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.UUID;

/**
 * @program: RookieSocialNetworking02
 * @description: 阿里云短信服务控制层
 * @author: 梁伟文
 * @create: 2020-08-24 18:44
 **/
@Controller
@RequestMapping("sms")
public class SmsApiController {

    @Autowired
    SendSms sendSms;
    @Autowired
    JedisPool jedisPool;

    @RequestMapping(value = "sendSms" , produces = "text/html; charset=utf-8")
    @ResponseBody
    public String sendCode(String phone){
        Jedis jedis = jedisPool.getResource();
        String code = jedis.get(phone);
        if(!StringUtils.isEmpty(code)){
            return "已存在,还没有过期";
        }

        code = UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",code);

        boolean b = sendSms.send(phone, "SMS_200194001", map);
        if(b){
            jedis.setex(phone,300,code);
            jedis.close();
            return "发送成功";
        }else{
            jedis.close();
            return "发送失败";
        }
    }
}
